package vip.xiaonuo.tasks;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.pojo.httpclient.ReturnJsonRemote;
import vip.xiaonuo.core.timer.TimerTaskRunner;
import vip.xiaonuo.core.util.DateUtils;
import vip.xiaonuo.core.util.OkHttpUtils;
import vip.xiaonuo.core.util.OkHttpUtils.ReqType;
import vip.xiaonuo.facedoor.modular.devicehistory.entity.DeviceHistory;
import vip.xiaonuo.facedoor.modular.devicehistory.service.DeviceHistoryService;
import vip.xiaonuo.facedoor.modular.idcardhistory.entity.IdCardHistory;
import vip.xiaonuo.facedoor.modular.idcardhistory.service.IdCardHistoryService;
import vip.xiaonuo.facedoor.modular.visitorhistory.entity.VisitorHistory;
import vip.xiaonuo.facedoor.modular.visitorhistory.service.VisitorHistoryService;
import vip.xiaonuo.tasks.remote.DeviceHistoryDto;
import vip.xiaonuo.tasks.remote.IdCardHistoryDto;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 云平台消息推送
 */
@Component
@Slf4j
public class RemotePushTask implements TimerTaskRunner {

    @Autowired
    private IdCardHistoryService idCardHistoryService;

    @Resource
    private DeviceHistoryService deviceHistoryService;

    @Resource
    private VisitorHistoryService visitorHistoryService;

    private volatile boolean canRun = true;

    @Override
    public void action(String taskId, String taskParam) {
        execute();
    }

    private void execute() {
        try {
            if (!canRun) {
                log.error("云平台推送任务正在执行中，跳过本次执行！");
                return;
            }
            canRun = false;
            // 参数配置
            String remote_push_ip = ConstantContextHolder.getSysConfig("REMOTE_PUSH_IP", String.class, true);
            String remote_push_port = ConstantContextHolder.getSysConfig("REMOTE_PUSH_PORT", String.class, true);
            String remote_id_card_push_contro = ConstantContextHolder.getSysConfig("REMOTE_ID_CARD_PUSH_CONTRO", String.class, true);
            String remote_device_push_contro = ConstantContextHolder.getSysConfig("REMOTE_DEVICE_PUSH_CONTRO", String.class, true);
            String imagePath = ConstantContextHolder.getSysConfig("SNOWY_FILE_UPLOAD_PATH_FOR_WINDOWS", String.class, true);
            String remoteCode = ConstantContextHolder.getSysConfig("REMOTE_CODE", String.class, true);
            String idCardPushUrl = "http://" + remote_push_ip + ":" + remote_push_port + remote_id_card_push_contro;
            String deivcePushUrl = "http://" + remote_push_ip + ":" + remote_push_port + remote_device_push_contro;
            imagePath = imagePath + "/defaultBucket/";

            // 通行记录数据获取
            List<IdCardHistory> idCardHistories = idCardHistoryService.list(new LambdaQueryWrapper<IdCardHistory>().ne(IdCardHistory::getPushFlag, 1).orderByDesc(IdCardHistory::getCreateTime).last(" limit 1000"));
            List<DeviceHistory> deviceHistories = deviceHistoryService.list(new LambdaQueryWrapper<DeviceHistory>().ne(DeviceHistory::getPushFlag, Boolean.TRUE).orderByDesc(DeviceHistory::getCreateTime).last(" limit 1000"));
            List<VisitorHistory> visitorHistories = visitorHistoryService.list(new LambdaQueryWrapper<VisitorHistory>().ne(VisitorHistory::getPushFlag, Boolean.TRUE).orderByDesc(VisitorHistory::getCreateTime).last(" limit 1000"));

            // 数据推送
            upLoadIdcardHistory(imagePath, remoteCode, idCardHistories, idCardPushUrl);
            upLoadDeviceHistory(imagePath, remoteCode, deviceHistories, deivcePushUrl);
            uploadVisitorHistory(imagePath, remoteCode, visitorHistories, deivcePushUrl);
        } catch (Exception e) {
            log.error("云平台推送任务正在执行错误【{}】", ExceptionUtils.getMessage(e));
        } finally {
            canRun = true;
        }
    }

    @Override
    @XxlJob("RemotePushTask")
    public void executeXxlJob() {
        this.execute();
    }

    private void uploadVisitorHistory(String imagePath, String remoteCode, List<VisitorHistory> visitorHistories, String deivcePushUrl) throws Exception {

        for (VisitorHistory visitorHistory : visitorHistories) {
            try {
                DeviceHistoryDto deviceHistoryDto = new DeviceHistoryDto();
                BeanUtils.copyProperties(visitorHistory, deviceHistoryDto);
                deviceHistoryDto.setDeviceBaseId(visitorHistory.getDeviceBaseId() != null ? visitorHistory.getDeviceBaseId() + "" : null);
                deviceHistoryDto.setMemberId(visitorHistory.getVisitorId() != null ? visitorHistory.getVisitorId() + "" : null);
                deviceHistoryDto.setOfficeId(visitorHistory.getOrgId() != null ? visitorHistory.getVisitorId() + "" : null);
                deviceHistoryDto.setMemberName(visitorHistory.getVisitorName());
                deviceHistoryDto.setMemberType("1");
                deviceHistoryDto.setType(visitorHistory.getType() != null ? visitorHistory.getType() + "" : null);
                deviceHistoryDto.setVerifyType(visitorHistory.getVerifyType() != null ? visitorHistory.getVerifyType() + "" : null);
                deviceHistoryDto.setDeviceDate(DateUtils.formatDateTime(visitorHistory.getDeviceCurrentDate()));
                deviceHistoryDto.setCode(remoteCode);
                deviceHistoryDto.setRecordImg(visitorHistory.getImage());
                Map<String, Object> params = JSON.parseObject(JSON.toJSONString(deviceHistoryDto), Map.class);
                ReturnJsonRemote returnJson = OkHttpUtils.commonRequest(ReqType.POST, deivcePushUrl, params, null, StringUtils.isNotEmpty(visitorHistory.getImage()) ? new File(imagePath + visitorHistory.getImage().split("/")[2]) : null);
                if (ObjectUtil.equal(returnJson.getCode(), 200)) {
                    visitorHistory.setPushFlag(Boolean.TRUE);
                    visitorHistoryService.updateById(visitorHistory);
                } else {
                    log.error("访客上传记录失败【{}】", JSON.toJSONString(returnJson));
                }
            } catch (Exception e) {
                log.error("内部人员记录推送至云平台数据发生错误【{}】", ExceptionUtils.getMessage(e));
            }
        }
    }

    private void upLoadDeviceHistory(String imagePath, String remoteCode, List<DeviceHistory> deviceHistories, String deivcePushUrl) {
        for (DeviceHistory deviceHistory : deviceHistories) {
            try {
                DeviceHistoryDto deviceHistoryDto = new DeviceHistoryDto();
                BeanUtils.copyProperties(deviceHistory, deviceHistoryDto);
                deviceHistoryDto.setDeviceBaseId(deviceHistory.getDeviceBaseId() != null ? deviceHistory.getDeviceBaseId() + "" : null);
                deviceHistoryDto.setMemberId(deviceHistory.getMemberId() != null ? deviceHistory.getMemberId() + "" : null);
                deviceHistoryDto.setOfficeId(deviceHistory.getOrgId() != null ? deviceHistory.getOrgId() + "" : null);
                deviceHistoryDto.setMemberType("0");
                deviceHistoryDto.setMemberName(deviceHistory.getMemberName());
                deviceHistoryDto.setType(deviceHistory.getType() != null ? deviceHistory.getType() + "" : null);
                deviceHistoryDto.setVerifyType(deviceHistory.getVerifyType() != null ? deviceHistory.getVerifyType() + "" : null);
                deviceHistoryDto.setDeviceDate(DateUtils.formatDateTime(deviceHistory.getDeviceCurrentDate()));
                deviceHistoryDto.setCode(remoteCode);
                deviceHistoryDto.setRecordImg(deviceHistory.getImage());
                Map<String, Object> params = JSON.parseObject(JSON.toJSONString(deviceHistoryDto), Map.class);
                ReturnJsonRemote returnJson = OkHttpUtils.commonRequest(ReqType.POST, deivcePushUrl, params, null, StringUtils.isNotEmpty(deviceHistory.getImage()) ? new File(imagePath + deviceHistory.getImage().split("/")[2]) : null);
                if (ObjectUtil.equals(returnJson.getCode(), 200)) {
                    deviceHistory.setPushFlag(Boolean.TRUE);
                    deviceHistoryService.updateById(deviceHistory);
                } else {
                    log.error("内部人员上传记录失败【{}】", JSON.toJSONString(returnJson));
                }
            } catch (Exception e) {
                log.error("内部人员记录推送至云平台数据发生错误【{}】", ExceptionUtils.getMessage(e));
            }

        }
    }

    private void upLoadIdcardHistory(String imagePath, String remoteCode, List<IdCardHistory> idCardHistories, String idCardPushUrl) throws Exception {
        for (IdCardHistory idCardHistory : idCardHistories) {
            try {
                IdCardHistoryDto idCardHistoryDto = new IdCardHistoryDto();
                BeanUtils.copyProperties(idCardHistory, idCardHistoryDto);
                idCardHistoryDto.setCode(remoteCode);
                idCardHistoryDto.setId(idCardHistory.getIdCard());
                idCardHistoryDto.setDeviceId(idCardHistory.getDeviceBaseId() != null ? idCardHistory.getDeviceBaseId() + "" : null);
                idCardHistoryDto.setDeviceName(idCardHistory.getDeviceName());
                idCardHistoryDto.setResult(idCardHistory.getComparedResult());
                idCardHistoryDto.setScore(idCardHistory.getComparedScore());
                idCardHistoryDto.setTime(DateUtils.formatDateTime(idCardHistory.getComparedDate()));
                idCardHistoryDto.setHsjcTime(idCardHistory.getHsjcTime() != null ? DateUtils.formatDateTime(idCardHistory.getHsjcTime()) : null);
                idCardHistoryDto.setRecordImg(idCardHistory.getImage());
                idCardHistoryDto.setIdCardImg(idCardHistory.getIdCardImg());
                Map<String, Object> params = JSON.parseObject(JSON.toJSONString(idCardHistoryDto), Map.class);
                ReturnJsonRemote returnJson = OkHttpUtils.commonRequest(ReqType.POST, idCardPushUrl, params, StringUtils.isNotEmpty(idCardHistory.getIdCardImg()) ? new File(imagePath + idCardHistory.getIdCardImg().split("/")[2]) : null, StringUtils.isNotEmpty(idCardHistory.getImage()) ? new File(imagePath + idCardHistory.getImage().split("/")[2]) : null);
                if (ObjectUtil.equals(returnJson.getCode(), 200)) {
                    idCardHistory.setPushFlag(1);
                    idCardHistoryService.updateById(idCardHistory);
                } else {
                    log.error("人证上传记录失败【{}】", JSON.toJSONString(returnJson));
                }
            } catch (Exception e) {
                log.error("人证记录推送至云平台数据发生错误【{}】", ExceptionUtils.getMessage(e));
            }
        }
    }
}


